﻿using System.Security.Claims;
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Http;

namespace Gateway.Infrastructure.Provider.Operator;

/// <summary>
/// 审计操作人信息提供者
/// </summary>
public class OperatorProvider : IOperatorProvider
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="httpContextAccessor"></param>
    public OperatorProvider(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    public Operator GetOperator()
    {
        var operatorId = string.Empty;
        var operatorName = string.Empty;
        var roleIds = string.Empty;
        if (_httpContextAccessor.HttpContext != null)
        {
            var currentUser = _httpContextAccessor.HttpContext.User;
            var isAuthenticated = currentUser.Identity?.IsAuthenticated ?? false;
            if (isAuthenticated)
            {
                operatorId = currentUser.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier)?.Value ??
                             string.Empty;
                operatorName = currentUser.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Name)?.Value ?? string.Empty;
                roleIds = currentUser.Claims.FirstOrDefault(x => x.Type.Equals("roleId"))?.Value ?? string.Empty;
            }
        }

        return new Operator
        {
            OperatorId = operatorId,
            OperatorName = operatorName,
            RoleIds = roleIds,
            Ip = GetIp(_httpContextAccessor.HttpContext)
        };
    }

    /// <summary>
    /// 获取ip
    /// </summary>
    /// <param name="httpContext"></param>
    /// <returns></returns>
    private string GetIp(HttpContext httpContext)
    {
        if (httpContext == null)
            return "";
        string result = httpContext.Request.Headers["X-Forwarded-For"];
        if (!string.IsNullOrEmpty(result))
        {
            //可能有代理 
            if (result.IndexOf(".", StringComparison.Ordinal) == -1) //没有“.”肯定是非IPv4格式 
                result = null;
            else
            {
                if (result.IndexOf(",", StringComparison.Ordinal) != -1)
                {
                    //有“,”，估计多个代理。取第一个不是内网的IP。 
                    result = result.Replace(" ", "").Replace("'", "");
                    string[] temparyip = result.Split(",;".ToCharArray());
                    for (int i = 0; i < temparyip.Length; i++)
                    {
                        if (IsIpAddress(temparyip[i])
                            && temparyip[i].Substring(0, 3) != "10."
                            && temparyip[i].Substring(0, 7) != "192.168"
                            && temparyip[i].Substring(0, 7) != "172.16.")
                        {
                            return temparyip[i]; //找到不是内网的地址 
                        }
                    }
                }
                else if (IsIpAddress(result)) //代理即是IP格式 
                    return result;
                else
                    result = null; //代理中的内容 非IP，取IP 
            }
        }

        if (string.IsNullOrEmpty(result))
            result = httpContext.Request.Headers["REMOTE_ADDR"];
        if (string.IsNullOrEmpty(result))
            result = httpContext.Request.Headers["X-Real-IP"];
        if (string.IsNullOrEmpty(result))
            result = httpContext.Connection?.RemoteIpAddress?.ToString();
        return result;
    }

    /// <summary>
    /// 判断是否是IP地址格式 0.0.0.0
    /// </summary>
    /// <param name="str1">待判断的IP地址</param>
    /// <returns>true or false</returns>
    private bool IsIpAddress(string str1)
    {
        if (string.IsNullOrEmpty(str1) || str1.Length < 7 || str1.Length > 15) return false;
        string regexFormat = @"^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$";
        Regex regex = new Regex(regexFormat, RegexOptions.IgnoreCase);
        return regex.IsMatch(str1);
    }
}